package com.example.tuike.service;

import com.example.tuike.mapper.UserMapper;
import com.example.tuike.entity.User;
import io.jsonwebtoken.security.Password;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/1/28 17:06

 * @Version 1.0*/
@Service
public class UserService {
    private final UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Transactional
    public User createUser(User user) {
        if (userMapper.findByUsername(user.getUsername()) != null) {//判断用户已经存在
            throw new IllegalArgumentException("用户名已存在");
        }
        user.setIsDeleted(0);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
        userMapper.insert(user);
        return user;
    }

    public User getUserById(Integer userId) {
        return userMapper.findById(userId);
    }

    public User getUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Transactional
    public void updateUser(User user) {
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.update(user);
    }

    @Transactional
    public void deleteUser(Integer userId) {
        userMapper.softDelete(userId);
    }
}
